import React, { useState, useEffect, useImperativeHandle, useRef } from 'react';
import { getConfig } from './Helper';
import useECharts from './useECharts';
import { TRTooltip } from '@/components';
import PropTypes from 'prop-types';
import { ToFixed } from './utils';

function TRECharts({
  data,
  cRef,
  coord = true,
  menucode = 3,
  coordRange = [],
  getPointPosition = () => {},
  type = 'column',
  TooltipFlag = true,
  minusHeight = 0,
  unit = '',
  initHeight = 0,
  suffixText = '',
  prefixText = '',
  seriesName = false,
  toolTipStyle = {},
  dragLineId = '', //拖拽线Id
  dragChangeList = () => {},
  tableList = [],
  keys = {},
  startValue = 0,
}) {
  const __tooltip_ = useRef();
  const chartRef = useRef(null);
  let barMinHeight = 16;
  const [clientHeight, setHeight] = useState(
    type === 'column' ? 600 : document.body.clientHeight - minusHeight,
  );
  const handleToopFormatter = (params, xAxis) => {
    const [data] = params;
    let array = [];
    if (menucode === 'DianJiaXinXiWeiHu' || menucode === 'PiFaGouDianHeYueGuanLi') {
      let name = '';
      if (typeof xAxis === 'object') {
        name = xAxis.data && xAxis.data[0];
      } else {
        name = params[params.length - 1].name;
      }
      let _params =
        params[0]?.seriesIndex != null ? params.filter((item) => item.axisDim === 'x') : params;
      _params.map((item) => {
        let value = item?.value || (item?.data[0] && item?.data[0].value) || '-';
        let name = seriesName ? item.seriesName || item.name : '';
        array.push({
          value: prefixText ? `${value}${prefixText}` : value,
          name: name === 'name' ? '' : name,
          color: item.color || '#1E7CE8',
        });
      });
      __tooltip_.current && __tooltip_.current.show(name, array);
    } else if (menucode === 'FuZhuFuWuGongLvShenBao') {
      let name = '';
      if (typeof xAxis === 'object') {
        name = xAxis.data && xAxis.data[0];
      } else {
        name = params[params.length - 1].name;
      }
      let array = params.map((item) => {
        let { color, name, seriesName = '', data } = item;
        return {
          color,
          name: seriesName || name,
          value:
            data[0]?.value != null
              ? ToFixed(data[0]?.value, 4)
              : data?.value
              ? ToFixed(data?.value, 4)
              : ToFixed(item?.value, 4) || '-',
        };
      });
      __tooltip_.current && __tooltip_.current.show(name, array);
    } else if (menucode === 'hhh') {
      let name = '';
      if (typeof xAxis === 'object') {
        name = xAxis.data && xAxis.data[startValue];
      } else {
        name = params[params.length - 1].name;
      }
      let array = params.map((item) => {
        let { color, name, seriesName = '', data } = item;
        return {
          color,
          name: seriesName || name,
          value:
            data[0]?.value != null
              ? ToFixed(data[0]?.value, 3)
              : data?.value
              ? ToFixed(data?.value, 3)
              : ToFixed(item?.value, 3) || '-',
        };
      });
      __tooltip_.current && __tooltip_.current.show(name, array);
    } else {
      const { name, value } = data;
      array.push({ value: `${value}%`, name, color: data.color || '#1E7CE8' });
      __tooltip_.current && __tooltip_.current.show(name, array);
    }
  };

  const config = getConfig(data, handleToopFormatter, coord, menucode, unit, keys, startValue);

  let { height, _chartInstance } = useECharts({
    chartRef,
    config,
    getPointPosition,
    coordRange,
    coord,
    type,
    minusHeight,
    initHeight,
    dragLineId, //拖拽Id
    dragChangeList, //拖拽回调函数
    tableList,
  });
  useEffect(() => {
    if (TooltipFlag && Object.keys(data).length > 0) {
      if (menucode === 'DianJiaXinXiWeiHu' || menucode === 'PiFaGouDianHeYueGuanLi') {
        handleToopFormatter(config.series, config.xAxis);
      } else if (menucode === 'hhh' || menucode === 'FuZhuFuWuGongLvShenBao') {
        handleToopFormatter(config.series, config.xAxis);
      } else {
        handleToopFormatter(config.series[0].data);
      }
    }
  }, [data]);

  useEffect(() => {
    let timer = null;
    if (config.series.length > 0 && type == 'row') {
      let len = Array.from(new Set(config.series.map((item) => item.stack || item.name))).length;
      let _height = Number(barMinHeight) * len * Number(config.series[0].data.length);
      timer = setTimeout(() => {
        setHeight(_height + 200);
      }, 500);
    } else {
      setHeight(height);
    }
    return () => {
      clearTimeout(timer);
    };
  }, [config]);

  useImperativeHandle(
    cRef,
    () => ({
      chartInstance: () => _chartInstance(),
      getHeight: type == 'row' ? clientHeight : height > 600 ? height : 600,
    }),
    [config, clientHeight, height, _chartInstance],
  );

  return (
    <div>
      {TooltipFlag && <TRTooltip ref={__tooltip_} suffixText={suffixText} />}
      <div
        style={{
          ...toolTipStyle,
          width: '100%',
          height: type == 'row' ? clientHeight : height > 600 ? height : initHeight || 600,
        }}
        ref={chartRef}
      />
    </div>
  );
}

TRECharts.propTypes = {
  data: PropTypes.array,
  cRef: PropTypes.string,
  coord: PropTypes.bool,
  menucode: PropTypes.string,
  coordRange: PropTypes.array,
  getPointPosition: PropTypes.func,
  type: PropTypes.string,
  TooltipFlag: PropTypes.bool,
  minusHeight: PropTypes.number,
  unit: PropTypes.string,
  initHeight: PropTypes.number,
  suffixText: PropTypes.string,
  prefixText: PropTypes.string,
  seriesName: PropTypes.bool,
  toolTipStyle: PropTypes.object,
  dragLineId: PropTypes.number,
  dragChangeList: PropTypes.func,
  tableList: PropTypes.array,
  keys: PropTypes.object,
  startValue: PropTypes.number,
};
export default TRECharts;
